package modeleIndexation;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;

import Main.Mysql;

public class TermesIndex {
	private Mysql bdd = Mysql.getInstance();
	private Hashtable<String, List<InfosTermeIndex>> liste;

	public TermesIndex() {
		liste = new Hashtable<String, List<InfosTermeIndex>>();
	}
	
	public void addTerme (String terme, NoeudIndex noeud, int pos) {
		if (liste.containsKey(terme)) {
			ArrayList<InfosTermeIndex> listNoeuds = (ArrayList<InfosTermeIndex>) liste.get(terme);
			if ( !listNoeuds.isEmpty() && ( (InfosTermeIndex) listNoeuds.get(listNoeuds.size()-1)).getNoeud().equals(noeud)) {
				((InfosTermeIndex) listNoeuds.get(listNoeuds.size()-1)).addPosition(pos);
			} else {
				InfosTermeIndex inf = new InfosTermeIndex(noeud);
				inf.addPosition(pos);
				listNoeuds.add (inf);
			}
		} else {
			InfosTermeIndex inf = new InfosTermeIndex(noeud);
			inf.addPosition(pos);
			List<InfosTermeIndex> lst = new ArrayList<InfosTermeIndex>();
			lst.add(inf);
			liste.put(terme, lst);
		}
	}
	
	public Set<String> getTermes () {
		return this.liste.keySet();
	}
	
	public void toBdd () {
		Object[] termes = this.liste.keySet().toArray();
		for (int i=0;i<termes.length;i++){
			if (i %1000 == 0) {
				System.out.println(i/1000);
			}
			/* insertion du terme */
			String req = "INSERT INTO Termes (terme) VALUES ('" + (String) termes[i] + "');" ;
			bdd.executeInsert(req);
			
	  		String queryID = "SELECT LAST_INSERT_ID();";
			int id = Integer.parseInt((String) bdd.getResultSet(bdd.executeSelect(queryID)).get(0).get(0));
		
			/* insertion des relations terme-noeud */
			for (int j=0; j<liste.get((String)termes[i]).size();j++) {
				req = "INSERT INTO TermeNoeud (idTerme, idNoeud, frequence) VALUES " 
					+ "(" + id + ", " + liste.get((String)termes[i]).get(j).getNoeud().getID() + ", " 
					+ liste.get((String)termes[i]).get(j).getPositions().size() + ");" ;
				bdd.executeInsert(req);
				
				queryID = "SELECT LAST_INSERT_ID();";
				int idTN = Integer.parseInt((String) bdd.getResultSet(bdd.executeSelect(queryID)).get(0).get(0));
				
				req = "INSERT INTO PositionTerme (idTermeNoeud, position) VALUES ";
				for (int k=0;k<liste.get((String)termes[i]).get(j).getPositions().size();k++) {
					req += ((k==0)?"":",") + "(" + idTN + ", " + liste.get((String)termes[i]).get(j).getPositions().get(k) + ")" ;
				}
				req+=";";
				
				try{
					bdd.executeSpecialInsert(req);
				}catch(Exception ex)
				{
					System.out.println("Mot : " +(String)termes[i]);
					for (int k=0;k<liste.get((String)termes[i]).get(j).getPositions().size();k++) {
						System.out.println (liste.get((String)termes[i]).get(j).getPositions().get(k));
					}
				}
			}
		}
	}
	
}
